package com.zahb.qadx.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.zahb.qadx.MainActivity;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.ImageUtil;
import com.zahb.qadx.util.QRCodeUtil;
import com.zahb.qadx.util.WebViewHelper;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ChoiceExamPublishSuccessActivity extends BaseActivity {

    @BindView(R.id.iv_qr_code)
    AppCompatImageView mIvQrCode;
    @BindView(R.id.tv_name)
    AppCompatTextView mTvName;
    @BindView(R.id.tv_time)
    AppCompatTextView mTvTime;

    private Bitmap mQrCodeBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTvName.setText(getIntent().getStringExtra("examName"));
        mTvTime.setText(getIntent().getStringExtra("startTime"));
        mTvTime.append(" - ");
        mTvTime.append(getIntent().getStringExtra("endTime"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mQrCodeBitmap != null && !mQrCodeBitmap.isRecycled()) {
            mQrCodeBitmap.recycle();
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_choice_exam_publish_success;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        String baseUrl = WebViewHelper.getBaseUrl();
        String url = baseUrl + "system/login?actionType=1&actionId=" + getIntent().getIntExtra("examId", -1);
        int width = DisplayUtil.dip2px(200f);
        int height = DisplayUtil.dip2px(200f);
        mQrCodeBitmap = QRCodeUtil.createQRCodeBitmap(
                url, width, height, "UTF-8", "H", "0",
                Color.BLACK, Color.WHITE, null, 0.2f, null);
        mIvQrCode.setImageBitmap(mQrCodeBitmap);
        mIvQrCode.setOnLongClickListener(v -> {
            imgChooseDialog();
            return true;
        });
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.publish_exam;
    }

    @OnClick({R.id.tv_view_details, R.id.tv_back_to_main})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_view_details:
                ViewExamDetailsActivity.actionStart(getContext(), getIntent().getIntExtra("examId", -1));
                break;
            case R.id.tv_back_to_main: {
                Intent intent = new Intent(getContext(), MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
                finish();
            }
            break;
        }
    }

    /**
     * 长按二维码图片弹出选择框（保存或分享）
     */
    private void imgChooseDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("选择")
                .setSingleChoiceItems(new String[]{"存储至手机", "分享"}, -1, (dialog, which) -> {
                    switch (which) {
                        case 0:// 存储
                            checkAndSaveImg();
                            break;
                        case 1:// 分享
                            shareImg(mQrCodeBitmap);
                            break;
                    }
                    dialog.dismiss();
                }).create().show();
    }

    private void checkAndSaveImg() {
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x101);
        } else {
            saveImg(mQrCodeBitmap);
        }
    }

    /**
     * 保存图片至本地
     *
     * @param bitmap 要保存的二维码
     */
    private void saveImg(Bitmap bitmap) {
        String fileName = "qr_" + System.currentTimeMillis() + ".jpg";
        boolean isSaveSuccess = ImageUtil.saveImageToGallery(getContext(), bitmap, fileName);
        if (isSaveSuccess) {
            showBindToast("图片已保存至本地");
        } else {
            showBindToast("保存图片失败，请稍后重试");
        }
    }

    /**
     * 分享图片(直接将bitmap转换为Uri)
     *
     * @param bitmap 要分享的二维码
     */
    private void shareImg(Bitmap bitmap) {
        Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null));
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("image/*");//设置分享内容的类型
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        intent = Intent.createChooser(intent, "分享");
        startActivity(intent);
    }

    public static void actionStart(Context context, int examId, String examName, String startTime, String endTime) {
        Intent intent = new Intent(context, ChoiceExamPublishSuccessActivity.class);
        intent.putExtra("examId", examId);
        intent.putExtra("examName", examName);
        intent.putExtra("startTime", startTime);
        intent.putExtra("endTime", endTime);
        context.startActivity(intent);
    }
}
